package com.lzx.action;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.lzx.actionform.UploadForm;

public class UploadAction extends Action {

	// @Override
	// public ActionForward execute(ActionMapping mapping, ActionForm form,
	// HttpServletRequest request, HttpServletResponse response)
	// throws Exception {
	// // TODO Auto-generated method stub
	// UploadForm uploadForm = (UploadForm) form;
	// uploadForm.getUploadFile();
	//
	// return mapping.findForward("success");
	// }

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		    String ss;
		    while( (ss=br.readLine()) != null) {
		    	System.out.print(ss);
		    	System.out.println();
		  }
	
		
		
		
		
		
		request.setCharacterEncoding("utf-8");
		// UploadForm uForm = (UploadForm) form;
		UploadForm uForm = (UploadForm) form;
		
		String s = request.getParameter("name");
	
		System.out.println(s);
		PrintWriter out = null;

		try {
			response.setCharacterEncoding("utf-8");
			out = response.getWriter();
			out.println("上传结果：");
			saveFile(uForm.getUploadFile()); // 将上传文件保存到指写的路径（在web.xml中配置）
			out.println("name:" + request.getParameter("name"));
			out.println("上传文件成功.");
			out.println("Referer: " + request.getHeader("Referer"));
		} catch (Exception e) {
			System.out.println(e);
			out.println(e.getMessage());
		}
		return null;
	}

	/**
	 * 
	 * @param formFile
	 * @throws Exception
	 */
	protected void saveFile(FormFile formFile) throws Exception {

		// 从web.xml文件中获得指定的上传路径
		String path = this.getServlet().getServletConfig().getInitParameter(
				"uploadPath");

		InputStream in = formFile.getInputStream(); // 获得上传文件的InputStream

		// 在服务端指定的上传路径中建立一个空的文件（文件名为getFileName()方法返回的值）
		FileOutputStream fout = new FileOutputStream(path
				+ formFile.getFileName());

		byte buffer[] = new byte[8192];
		int count = 0;

		// 开始向上传路径中刚建立的文件写入数据，每次写8k字节
		while ((count = in.read(buffer)) > 0) {
			fout.write(buffer, 0, count);
		}

		fout.close();
		formFile.destroy(); // 上传成功后，销毁当前上传文件的资源

	}

}
